#include <stdint.h>
#include <string.h>

#include "hdf_device_desc.h" 
#include "hdf_log.h"         
#include "device_resource_if.h"
#include "osal_io.h"
#include "osal_mem.h"
#include "osal_time.h"

#define TITLE "凉州词二首·其一·王焕之"
#define MY_TEXT "黄河远上白云间，一片孤城万仞山。羌笛何须怨杨柳，春风不度玉门关。"

struct myText
{
    struct HdfSBuf *title;
    struct HdfSBuf *text;
};

struct myText g_text_data;


int32_t TextDriverDispatch(struct HdfDeviceIoClient *client, int cmdCode, struct HdfSBuf *data, struct HdfSBuf *reply)
{
    char *replay_buf;
    HDF_LOGE("Text driver dispatch");
    if (client == NULL || client->device == NULL)
    {
        HDF_LOGE("Text driver device is NULL");
        return HDF_ERR_INVALID_OBJECT;
    }
    switch (cmdCode)
    {
    case 1:
        HdfSbufWriteString(g_text_data.title,TITLE);
        HdfSbufWriteString(g_text_data.text,MY_TEXT);
        replay_buf =  OsalMemAlloc(200);
        (void)memset_s(replay_buf, 200, 0, 200);
        sprintf(replay_buf,"{\"title\":%s,\"mytext\":%s}",\
                            g_text_data.title,           \
                            g_text_data.text);

        if (!HdfSbufWriteString(reply, replay_buf))                
        {
            HDF_LOGE("replay is fail");
            return HDF_FAILURE;
        }
        OsalMemFree(replay_buf);
        break;
    default:
        return HDF_FAILURE;
    }
    return HDF_SUCCESS;
}

static int32_t Hdf_Text_DriverBind(struct HdfDeviceObject *deviceObject)
{
    if (deviceObject == NULL)
    {
        HDF_LOGE("text driver bind failed!");
        return HDF_ERR_INVALID_OBJECT;
    }
    static struct IDeviceIoService textDriver = { 
        .Dispatch = TextDriverDispatch,
    };
    deviceObject->service = (struct IDeviceIoService *)(&textDriver);
    HDF_LOGD("Text driver bind success");
    return HDF_SUCCESS;
}

static int32_t Hdf_Text_DriverInit(struct HdfDeviceObject *device)
{
    return HDF_SUCCESS;
}

void Hdf_Text_DriverRelease(struct HdfDeviceObject *deviceObject)
{
    if (deviceObject == NULL)
    {
        HDF_LOGE("Text driver release failed!");
        return;
    }
    HDF_LOGD("Text driver release success");
    return;
}


struct HdfDriverEntry g_text_driver_entry = {
    .moduleVersion = 1,
    .moduleName = "HDF_TEXT",
    .Bind = Hdf_Text_DriverBind,
    .Init = Hdf_Text_DriverInit,
    .Release = Hdf_Text_DriverRelease,
};

//将驱动入口注册到HDF框架中
HDF_INIT(g_text_driver_entry);